import os
import time
import threading
from datetime import datetime, timedelta
from config.settings import (
    UPLOAD_FOLDER, COMPRESSED_FOLDER, CONVERTED_FOLDER, 
    LOG_DIR, FILE_RETENTION_DAYS, LOG_RETENTION_DAYS
)
from utils.logger import logger

def cleanup_old_files():
    """
    清理超过保留时间的文件
    """
    # 服务启动时立即执行一次清理
    first_run = True
    
    while True:
        try:
            if not first_run:
                now = datetime.now()
                # 计算下次清理时间（明天0点）
                next_day = now + timedelta(days=1)
                next_cleanup = datetime(next_day.year, next_day.month, next_day.day, 0, 0, 0)
                sleep_seconds = (next_cleanup - now).total_seconds()
                
                logger.info(f"文件清理服务将在 {sleep_seconds/3600:.1f} 小时后运行")
                time.sleep(sleep_seconds)
            
            logger.info("开始清理过期文件...")
            
            # 获取当前时间作为基准
            current_time = datetime.now()
            retention_cutoff = current_time - timedelta(days=FILE_RETENTION_DAYS)
            
            # 清理业务文件
            deleted_files = 0
            for folder in [UPLOAD_FOLDER, COMPRESSED_FOLDER, CONVERTED_FOLDER]:
                if not os.path.exists(folder):
                    continue
                    
                for filename in os.listdir(folder):
                    filepath = os.path.join(folder, filename)
                    if os.path.isfile(filepath):
                        try:
                            file_mtime = datetime.fromtimestamp(os.path.getmtime(filepath))
                            logger.info("文件: " + filepath + ", 创建时间: " + str(file_mtime) + ", 保留截止时间: " + str(retention_cutoff))
                            # 只删除在保留截止时间之前创建的文件
                            if file_mtime < retention_cutoff:
                                # 检查文件是否正在使用（Windows系统）
                                if os.name == 'nt':
                                    try:
                                        # 尝试以独占模式打开文件，如果成功则说明文件未被使用
                                        with open(filepath, 'rb+') as f:
                                            os.remove(filepath)
                                            deleted_files += 1
                                            logger.debug(f"已删除过期业务文件: {filepath}")
                                    except IOError:
                                        logger.warning(f"业务文件可能正在使用，跳过删除: {filepath}")
                                        continue
                                else:
                                    os.remove(filepath)
                                    deleted_files += 1
                                    logger.debug(f"已删除过期业务文件: {filepath}")
                                    
                        except Exception as e:
                            logger.error(f"处理业务文件 {filepath} 时出错: {str(e)}")
                            continue
            
            # 清理日志文件
            log_retention_cutoff = current_time - timedelta(days=LOG_RETENTION_DAYS)
            deleted_logs = 0
            
            if os.path.exists(LOG_DIR):
                for logname in os.listdir(LOG_DIR):
                    logpath = os.path.join(LOG_DIR, logname)
                    if os.path.isfile(logpath) and logname.startswith('app_'):
                        try:
                            log_mtime = datetime.fromtimestamp(os.path.getmtime(logpath))
                            if log_mtime < log_retention_cutoff:
                                os.remove(logpath)
                                deleted_logs += 1
                                logger.debug(f"已删除过期日志文件: {logpath}")
                        except Exception as e:
                            logger.error(f"删除日志文件 {logpath} 失败: {str(e)}")
            
            logger.info(f"文件清理完成，共删除 {deleted_files} 个过期业务文件和 {deleted_logs} 个过期日志文件")
            
            first_run = False
            
        except Exception as e:
            logger.error(f"文件清理服务出错: {str(e)}")
            logger.error(traceback.format_exc())
            time.sleep(60)  # 出错后等待1分钟再重试

def start_cleanup_thread():
    """
    启动文件清理线程
    """
    cleanup_thread = threading.Thread(target=cleanup_old_files, daemon=True)
    cleanup_thread.start()
    return cleanup_thread